from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate
from sqlalchemy.testing.plugin.plugin_base import logging

from config import Config
from internal.exception import CustomException
from internal.router import Router
from pkg.resp import Response, HttpCode, json
from pkg.sqlalchemy import SQLAlchemy
from internal.extension import loggIng_extension, redis_extension, celery_extension


class Http(Flask):
    def __init__(self, *args, config: Config, db: SQLAlchemy, router: Router, migrate: Migrate, **kwargs):
        super().__init__(*args, **kwargs)
        self.config.from_object(config)
        self.register_error_handler(Exception, self._register_error_handler)
        db.init_app(self)
        celery_extension.init_app(self)
        redis_extension.init_app(self)
        loggIng_extension.init_app(self)
        CORS(self, resources={
            r"/*": {
                "origins": "*",
                "supports_credentials": True,
            },
        })

        migrate.init_app(self, db, directory="internal/migration")
        router.reg_router(self)

    def _register_error_handler(self, error: Exception):
        # logging.error("An error occurred: %s", error, exc_info=True)
        if isinstance(error, CustomException):
            return json(
                Response(
                    code=error.code,
                    message=error.message,
                    data=error.data if error.data is not None else {},
                )
            )
        else:
            if self.debug:
                return error
            else:
                return json(Response(code=HttpCode.FAIL, message=str(error)))
